﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using YunCMS.BLL;
using YunCMS.Model;
using YunCMS.Common;

namespace YunCMS.Web.Admin.User
{
    public partial class SetPwd : System.Web.UI.Page
    {
        private YCUserBLL _bll = null;

        protected YCUserBLL BLL
        {
            get
            {
                if (_bll == null)
                {
                    _bll = new YCUserBLL();
                }
                return _bll;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int id;
                string _id = Request.QueryString["id"];
                if (!int.TryParse(_id, out id))
                    id = 0;

                ViewState["ID"] = id;
                BindControls(id);

            }
        }

        private void BindControls(int id)
        {
            if (BLL.IsExist(id))
            {
                YCUser model = BLL.GetYCUser(id);
                FillControls(model);
            }
            else
            {
                JScript.Alert("不存在该条记录", this);
            }
        }

        private void FillControls(YCUser model)
        {
            txtEmail.Text = model.Email.ToString();
            txtTelephone.Text = model.Telephone.ToString();
            txtRealName.Text = model.Name.ToString();
            txtMemo.Text = model.OtherInfo.ToString();
        }

        private void FillModel(YCUser model)
        {
            model.Password = YunCMSUtil.EncryptPwd(txtUserPwd.Text.Trim());
            model.Email = txtEmail.Text.Trim();
            model.Telephone = txtTelephone.Text.Trim();
            model.Name = txtRealName.Text.Trim();
            model.OtherInfo = txtMemo.Text.Trim();
        }

        protected void saveBt_Click(object sender, EventArgs e)
        {
            YCUser model;
            int i = 0, id;
            string action = Request.QueryString["action"];

            if (ViewState["ID"] != null)
            {
                id = System.Convert.ToInt32(ViewState["ID"]);
                model = BLL.GetYCUser(id);
                FillModel(model);

                if (YunCMSUtil.EncryptPwd(txtOldPwd.Text.Trim()) != model.Password)// todo: 加密
                {
                    JScript.Alert("旧密码不正确！", this);
                    return;
                }
                if (txtUserPwd.Text.Trim() != txtUserPwd1.Text.Trim())
                {
                    JScript.Alert("两次密码不一致！", this);
                    return;
                }

                i = BLL.Update(model);
            }

            if (i > 0)
            {
                Response.Redirect("../Center.aspx");
            }
        }
    }
}